package com.threeti.jiayusms.interfaces.facade;

import static org.springframework.util.CollectionUtils.isEmpty;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.threeti.jiayusms.domain.model.CommunicationMessage;
import com.threeti.jiayusms.domain.model.CommunicationRule;
import com.threeti.jiayusms.domain.model.CommunicationTime;
import com.threeti.jiayusms.domain.model.CommunicationVoice;
import com.threeti.jiayusms.domain.model.legacy.Condition;
import com.threeti.jiayusms.domain.model.legacy.ConditionType;
import com.threeti.jiayusms.domain.model.legacy.Customer;
import com.threeti.jiayusms.domain.model.legacy.Department;
import com.threeti.jiayusms.domain.model.legacy.Node;
import com.threeti.jiayusms.domain.model.legacy.Order;
import com.threeti.jiayusms.domain.model.legacy.ProductType;
import com.threeti.jiayusms.domain.model.legacy.SendAddress;
import com.threeti.jiayusms.domain.service.communicationmessage.CommunicationMessageQueryService;
import com.threeti.jiayusms.domain.service.communicationrule.CommunicationRuleQueryService;
import com.threeti.jiayusms.domain.service.communicationtime.CommunicationTimeQueryService;
import com.threeti.jiayusms.domain.service.communicationvoice.CommunicationVoiceQueryService;
import com.threeti.jiayusms.domain.service.legacy.JiaYuDBLegacyQueryService;
import com.threeti.jiayusms.domain.util.CommonUtils;
import com.threeti.jiayusms.domain.util.DateUtil;

@Service
public class JiaYuSystemQueryFacadeImpl implements JiaYuSystemQueryFacade {
  private static final Logger logger = LoggerFactory.getLogger(JiaYuSystemQueryFacadeImpl.class);
  
  @Autowired
  private CommunicationMessageQueryService msgQueryService;

  @Autowired
  private CommunicationRuleQueryService ruleQueryService;

  @Autowired
  private CommunicationVoiceQueryService voiceQueryService;

  @Autowired
  private CommunicationTimeQueryService timeQueryService;

  @Autowired
  private JiaYuDBLegacyQueryService legacyQueryService;

  @Override
  public String getMessageTemplateBy(String orderid, String msgTemplateId, String sendTimeId) {
    //取得短信模板元
    CommunicationMessage msgTemplateMeta = msgQueryService.findCommunicationMessageBy(msgTemplateId);

    String msg = msgTemplateMeta.getSmsContent();

    return process(orderid, sendTimeId, msg, false);
  }

  @Override
  public String getVoiceTemplateBy(String orderid, String voiceTemplateId, String sendTimeId) {
    CommunicationVoice voiceTemplateMeta = voiceQueryService.findCommunicationVoiceBy(voiceTemplateId);

    String msg = voiceTemplateMeta.getVoiceContent();

    return process(orderid, sendTimeId, msg, true);
  }

  private String process(String orderid, String sendTimeId, String msg, boolean isForVoiceTuning) {
    String oldmsg = msg;
    CommunicationTime time = timeQueryService.findCommunicationTimeBy(sendTimeId);
    //Date availDate = time.getAvailDate();

    String[] rtnDate =
      DateUtil.querySendTime2(time.getTimeSegment());

    if (rtnDate == null) {
      logger.error("日期无效或日期计算产生异常");
      return "x";
    }
    
    //取得运单
    Order order = null;
    try {
      order = legacyQueryService.findOrderBy(orderid);
    } catch (Exception e) {
      logger.error("运单不存在或取得运单时发生异常", e);
      return "x";
    }
    
    msg = msg.replaceAll("\\{0\\}", DateUtil.DEFAULT_TIME_FORMATTER_CN.format(new Date()));//系统函数置换

    //运单表元置换
    msg = msg.replaceAll("\\{orderid\\}", order.getOrderid());//运单号置换
    msg = msg.replaceAll("\\{cargono\\}", order.getCargono());//货号置换
    msg = msg.replaceAll("\\{cargoname\\}", order.getCargoname());//货物名称置换
    msg = msg.replaceAll("\\{cargocount\\}", String.valueOf(order.getCargocount()));//件数置换
    msg = msg.replaceAll("\\{clientid\\}", order.getClientid());//TODO 客户编号置换
    msg = msg.replaceAll("\\{shipper\\}", order.getShipper());//发货人置换
    msg = msg.replaceAll("\\{shipperphone\\}", order.getShipperphone());//发货人电话置换
    msg = msg.replaceAll("\\{shipperMP\\}", order.getShipperMP());//发货人手机置换
    msg = msg.replaceAll("\\{signaturer\\}", order.getSignaturer());//收货人置换
    msg = msg.replaceAll("\\{signaturephone\\}", order.getSignaturephone());//收货人电话置换
    msg = msg.replaceAll("\\{signatureMP\\}", order.getSignatureMP());//收货人手机置换
    msg = msg.replaceAll("\\{totalfee\\}", String.valueOf(order.getTotalfee()));//总运费置换
    msg = msg.replaceAll("\\{sendfee\\}", String.valueOf(order.getSendfee()));//已付费置换
    msg = msg.replaceAll("\\{arrivefee\\}", String.valueOf(order.getArrivefee()));//提付费置换
    msg = msg.replaceAll("\\{monthfee\\}", String.valueOf(order.getMonthfee()));//月结费置换
    msg = msg.replaceAll("\\{gatherfee\\}", String.valueOf(order.getGatherfee()));//代收款置换
    msg = msg.replaceAll("\\{loaddeptid\\}", order.getLoaddeptid());//起运地公司编号置换
    msg = msg.replaceAll("\\{unloadeptid\\}", order.getUnloadeptid());//目的地公司编号置换
    msg = msg.replaceAll("\\{sendcargotype3\\}", order.getSendcargotype3());//送货方式（1-自提，2-送货）置换
    
    //额外取得收货地址
    SendAddress sendAddress = null;
    try {
      sendAddress = legacyQueryService.findSendAddressBy2(orderid);
      msg = msg.replaceAll("\\{sendaddress\\}", sendAddress.getSendaddress());//收货地址
    } catch (Exception e) {
      logger.error(" 收获地址不存在或取得收获地址时发生异常", e);
    }
    
    //客户表元置换
    try {
      Customer customer = legacyQueryService.findCustomerBy(order.getClientid());
      msg = msg.replaceAll("\\{clientid\\}", customer.getClientid());//客户编号置换
      msg = msg.replaceAll("\\{clientname\\}", customer.getClientname());//客户名称置换
      msg = msg.replaceAll("\\{simpleclientname\\}", customer.getSimpleclientname());//客户简称置换
      msg = msg.replaceAll("\\{SPphone\\}", customer.getSPphone());//手机号置换
    } catch (Exception e) {
      logger.error(" 客户不存在或取得客户时发生异常", e);
    }

    //组织结构表元置换
    try {
      Department loadDept = legacyQueryService.findDepartmentBy(order.getLoaddeptid());
      
      //System.out.println("Order目的地编号" + order.getUnloadeptid());
      Department unloadDept = legacyQueryService.findDepartmentBy(order.getUnloadeptid());
      //System.out.println("对应的" + unloadDept);
      
      if (loadDept != null) {
        msg = msg.replaceAll("\\{loaddept.deptcode\\}", loadDept.getDeptcode());//公司编号置换
        msg = msg.replaceAll("\\{loaddept.deptname\\}", loadDept.getDeptname());//公司名称置换
        msg = msg.replaceAll("\\{loaddept.simplename\\}", loadDept.getSimplename());//公司简称置换
        msg = msg.replaceAll("\\{loaddept.deptadd\\}", loadDept.getDeptadd());//公司地址置换
        msg = msg.replaceAll("\\{loaddept.sendphone\\}", loadDept.getSendphone());//发货电话置换
        msg = msg.replaceAll("\\{loaddept.arrivequeryphone\\}", loadDept.getArrivequeryphone());//到货电话置换
        msg = msg.replaceAll("\\{loaddept.servicephone\\}", loadDept.getServicephone());//服务电话置换
        msg = msg.replaceAll("\\{loaddept.city\\}", loadDept.getRelatedCity());//城市置换
      }
      if (unloadDept != null) {
        //组织结构表专指目的地->
        msg = msg.replaceAll("\\{deptcode\\}", unloadDept.getDeptcode());//公司编号置换
        msg = msg.replaceAll("\\{deptname\\}", unloadDept.getDeptname());//公司名称置换
        msg = msg.replaceAll("\\{simplename\\}", unloadDept.getSimplename());//公司简称置换
        if(sendAddress != null){
            msg = msg.replaceAll("\\{deptadd\\}", sendAddress.getSendaddress());//公司地址置换
        }else{
            msg = msg.replaceAll("\\{deptadd\\}", unloadDept.getDeptadd());//公司地址置换
        }
        msg = msg.replaceAll("\\{sendphone\\}", unloadDept.getSendphone());//发货电话置换
        msg = msg.replaceAll("\\{arrivequeryphone\\}", unloadDept.getArrivequeryphone());//到货电话置换
        msg = msg.replaceAll("\\{servicephone\\}", unloadDept.getServicephone());//服务电话置换
        //<-        
        
        msg = msg.replaceAll("\\{unloaddept.deptcode\\}", unloadDept.getDeptcode());//公司编号置换
        msg = msg.replaceAll("\\{unloaddept.deptname\\}", unloadDept.getDeptname());//公司名称置换
        msg = msg.replaceAll("\\{unloaddept.simplename\\}", unloadDept.getSimplename());//公司简称置换
        msg = msg.replaceAll("\\{unloaddept.deptadd\\}", unloadDept.getDeptadd());//公司地址置换
        msg = msg.replaceAll("\\{unloaddept.sendphone\\}", unloadDept.getSendphone());//发货电话置换
        msg = msg.replaceAll("\\{unloaddept.arrivequeryphone\\}", unloadDept.getArrivequeryphone());//到货电话置换
        msg = msg.replaceAll("\\{unloaddept.servicephone\\}", unloadDept.getServicephone());//服务电话置换
        msg = msg.replaceAll("\\{unloaddept.city\\}", unloadDept.getRelatedCity());//城市置换
      }
    } catch (Exception e) {
      logger.error(" 部门不存在或取得部门时发生异常", e);
    }

    if (isForVoiceTuning) {
      msg = CommonUtils.getNumberTransformed(msg, "");
    }
    /*logger.info(oldmsg);
    System.out.println(oldmsg);
    logger.info(rtnDate[0] + rtnDate[1] + msg);
    System.out.println(rtnDate[0] + rtnDate[1] + msg);*/
    return rtnDate[0] + rtnDate[1] + msg;
  }

  @Override
  public String getMessagePreviewBy(String nodeCode,
                                    String msgTemplateId,
                                    String ruleTemplateId,
                                    String timeTemplateId,
                                    String productTypeCode,
                                    String conditionTypeCode,
                                    String conditionCode,
                                    String communicationEnable) {
    return processPreview(nodeCode, msgTemplateId, ruleTemplateId, timeTemplateId, productTypeCode, conditionTypeCode,
        conditionCode, communicationEnable, true);
  }

  @Override
  public String getVoicePreviewBy(String nodeCode,
                                  String voiceTemplateId,
                                  String ruleTemplateId,
                                  String timeTemplateId,
                                  String productTypeCode,
                                  String conditionTypeCode,
                                  String conditionCode,
                                  String communicationEnable) {
    return processPreview(nodeCode, voiceTemplateId, ruleTemplateId, timeTemplateId, productTypeCode, conditionTypeCode,
        conditionCode, communicationEnable, false);
  }

  private String processPreview(String nodeCode,
                                String msgOrVoiceTemplateId,
                                String ruleTemplateId,
                                String timeTemplateId,
                                String productTypeCode,
                                String conditionTypeCode,
                                String conditionCode,
                                String communicationEnable,
                                boolean isMsgTemplate) {
    StringBuffer buffer = new StringBuffer();
    
    //节点
    List<Node> nodes = legacyQueryService.findAllNodes();
    if (!isEmpty(nodes)) {
      for (Node node : nodes) {
        if (nodeCode.equals(node.getNcode())) {
          buffer.append("节点：" + node.getNname());
          buffer.append("\n");
          break;
        }
      }
    } else {
      buffer.append("节点：");
      buffer.append("\n");
    }
    
    //短信模板
    if (isMsgTemplate) {
      CommunicationMessage msgTemplate = msgQueryService.findCommunicationMessageBy(msgOrVoiceTemplateId);
      if (msgTemplate != null) {
        buffer.append("短信描述：" + msgTemplate.getSmsDescription());
        buffer.append("\n");
        buffer.append("短信内容：" + msgTemplate.getSmsContent());
        buffer.append("\n");
      } else {
        buffer.append("短信描述：");
        buffer.append("\n");
        buffer.append("短信内容：");
        buffer.append("\n");
      }
    //语音模板
    } else {
      CommunicationVoice voiceTemplate = voiceQueryService.findCommunicationVoiceBy(msgOrVoiceTemplateId);
      if (voiceTemplate != null) {
        buffer.append("语音描述：" + voiceTemplate.getVoiceDescription());
        buffer.append("\n");
        buffer.append("语音内容：" + voiceTemplate.getVoiceContent());
        buffer.append("\n");
      } else {
        buffer.append("语音描述：");
        buffer.append("\n");
        buffer.append("语音内容：");
        buffer.append("\n");
      }
    }
    
    //通信规则
    CommunicationRule ruleTemplate = ruleQueryService.findCommunicationRuleBy(ruleTemplateId);
    if (ruleTemplate != null) {
      buffer.append("发送次数：" + ruleTemplate.getSendCount());
      buffer.append("\n");
      buffer.append("延迟时间：" + ruleTemplate.getSendInterval());
      buffer.append("\n");
    } else {
      buffer.append("发送次数：");
      buffer.append("\n");
      buffer.append("延迟时间：");
      buffer.append("\n");
    }
    
    //通信时间
    CommunicationTime timeTemplate = timeQueryService.findCommunicationTimeBy(timeTemplateId);
    if (timeTemplate != null) {
      buffer.append("是否工作日发送：" + (timeTemplate.getWorkFlag()==1?"是":"否"));
      buffer.append("\n");
      buffer.append("通信时间：" + timeTemplate.getTimeSegment());
      buffer.append("\n");
    } else {
      buffer.append("是否工作日发送：");
      buffer.append("\n");
      buffer.append("通信时间：");
      buffer.append("\n");
    }
    
    //通信启用
    if ("1".equals(communicationEnable)) {
      buffer.append("通信启用：是");
      buffer.append("\n");
    } else {
      buffer.append("通信启用：否");
      buffer.append("\n");
    }
    
    //产品类型
    List<ProductType> pTypes = legacyQueryService.findAllProductTypes();
    if (!isEmpty(pTypes)) {
      for (ProductType productType : pTypes) {
        if (productTypeCode.equals(productType.getPcode())) {
          buffer.append("产品类型：" + productType.getPname());
          buffer.append("\n");
          break;
        }
      }
    } else {
      buffer.append("产品类型：");
      buffer.append("\n");
    }
    
    //条件类型
    List<ConditionType> cTypes = legacyQueryService.findAllConditionTypes();
    if (!isEmpty(cTypes)) {
      for (ConditionType cType : cTypes) {
        if (conditionTypeCode.equals(cType.getCcode())) {
          buffer.append("条件类型：" + cType.getCname());
          buffer.append("\n");
          break;
        }
      }
    } else {
      buffer.append("条件类型：");
      buffer.append("\n");
    }
    
    //条件值
    List<Condition> conditions = legacyQueryService.findAllConditions();
    if (!isEmpty(conditions)) {
      for (Condition condition : conditions) {
        if (conditionCode.equals(condition.getCvcode())) {
          buffer.append("条件值：" + condition.getCvname());
          buffer.append("\n");
          break;
        }
      }
    } else {
      buffer.append("条件值：");
    }

    return buffer.toString();
  }

}
